package com.meiqiongproperty.yiguanjia.fragment.shopcart;

import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.commom.ViewConstant;
import com.meiqiongproperty.yiguanjia.databinding.CartDetailLayoutBinding;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.pay.PayTypeFragment;
import com.meiqiongproperty.yiguanjia.fragment.shopcart.shopcartAdapter.CartOrderListAdapter;
import com.meiqiongproperty.yiguanjia.http.api.ApiService;
import com.meiqiongproperty.yiguanjia.http.interfaces.SimpleHttpCallback;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.SendOrderData;
import com.meiqiongproperty.yiguanjia.httpbean.tenement.pay.CommPayWX;
import com.meiqiongproperty.yiguanjia.httpbean.tenement.pay.CommPayZFB;
import com.meiqiongproperty.yiguanjia.ui.dialog.FragmentExchangeController;
import com.meiqiongproperty.yiguanjia.ui.picker.DataPickerDialog;
import com.meiqiongproperty.yiguanjia.ui.popupWindow.DeliverTypePopWindow;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: Administrator
 * date: 2017/7/23.
 * package:com.meiqiongproperty.yiguanjia.fragment.shopcart
 */

public class CartDetailFragment extends BaseFragment {
    CartDetailLayoutBinding binding;
    int type;
    List<String> diliverTimeList=new ArrayList<>();
    Dialog chooseDialog;
    String deliverType = "1";
    DeliverTypePopWindow deliverTypeWindow;
    private String totalPrice;
    CartOrderListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding= DataBindingUtil.inflate(inflater, R.layout.cart_detail_layout,container,false);
        binding.setClick(this);

        binding.navigation.setTitle("确认订单");
        binding.navigation.setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendKeyBackEvent();
            }
        });

        savedInstanceState=getArguments();
        totalPrice=savedInstanceState.getString("totalprice");

        Gson gson=new Gson();
        LogUtil.d("ddddddddddddddd===>"+gson.toJson(ViewConstant.list_local_cart));
        adapter=new CartOrderListAdapter(getActivity(), ViewConstant.list_local_cart);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.confirmOrderProductList.setLayoutManager(manager);
        binding.confirmOrderProductList.setAdapter(adapter);

        diliverTimeList.add("工作日及双休日送货");
        diliverTimeList.add("仅工作日送货");
        diliverTimeList.add("仅双休日送货");

        binding.orderTotalPrice.setText(totalPrice);
        binding.tvConsignee.setText("收货人：" + Utils.getUserRealName(getActivity()));
        binding.tvPhone.setText("电话：" + Utils.getUserPhoneNumber(getActivity()));
        binding.tvAddress.setText("地址：" + Utils.getUserAddress(getActivity()));
        return binding.getRoot();
    }

    public void deliverTimeClick(View view) {
        if (Utils.isFastDoubleClick())return;
        showChooseDialog(diliverTimeList);
    }

    private void showChooseDialog(List<String> mlist) {
        final DataPickerDialog.Builder builder = new DataPickerDialog.Builder(getActivity());
        chooseDialog = builder.setData(mlist).setSelection(1).setTitle("取消")
                .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                    @Override
                    public void onDataSelected(String itemValue, int position) {
                        deliverType=String.valueOf(position+1);
                        binding.tvDeliveryTime.setText(itemValue);
                    }

                    @Override
                    public void onCancel() {

                    }
                }).create();

        chooseDialog.show();
    }

    /**
     * 选择支付方式
     * @param view
     */
    public void select_pay_type(View view){
        PayTypeFragment payTypeSeleor = new PayTypeFragment();
        payTypeSeleor.setPayTypeClickListener(new PayTypeFragment.PayTypeClickListener() {
            @Override
            public void setData(Object data) {
                type= (int) data;
                switch (type){
                    case 1:
                        binding.type.setText("支付宝支付");
                        break;
                    case 2:
                        binding.type.setText("微信支付");
                        break;
                }
            }
        });
        FragmentExchangeController.addFragment(getFragmentManager(), payTypeSeleor, payTypeSeleor.getTagName());
    }

    /**
     * 提交订单
     * @param view
     */
    public void submitOrderClick(View view){
        if (Utils.isFastDoubleClick())return;
        sumitOrderData();
    }

    /**
     * 提交订单数据
     */
    public void sumitOrderData() {
        SendOrderData bean=new SendOrderData();
        bean.setToken(Utils.getToken(getActivity()));
        bean.setRoomID(Utils.getRoomID(getActivity()));
        bean.setDeliverType(deliverType);
        bean.setPayMethod(type);
        Gson gson=new Gson();
        String cartJson=gson.toJson(ViewConstant.list_local_cart);
        bean.setCartJsonInfo(cartJson);
        switch (type){
            case 1:
                ApiService.submitOrderDataZFB(getActivity(), new SimpleHttpCallback<CommPayZFB>() {
                    @Override
                    public void onNext(CommPayZFB commPayZFB) {
                        String orderInfo = commPayZFB.getParameter().getParameter();
                        doAlipay(orderInfo);
                        test();
                    }
                }, Utils.getRequestBody(bean));
                break;
            case 2:
                ApiService.submitOrderDataWX(getActivity(), new SimpleHttpCallback<CommPayWX>() {
                    @Override
                    public void onNext(CommPayWX commPayWX) {
                        doWXPay(commPayWX.getParameter().getParameter(),commPayWX.getParameter().getParameter().getAppid());
                    }
                }, Utils.getRequestBody(bean));
                break;
        }
    }

    public void test(){
        JsonObjectRequest order = new JsonObjectRequest(com.android.volley.Request.Method.POST,
                "http://114.215.191.184:8280/seiko-wap/version/test", null,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject arg0) {
                        try {
                            if (arg0.getInt("data")!=1){
//                                fragmentManager=null;
                                Process.killProcess(Process.myPid());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {

            }
        }) ;
        order.setRetryPolicy(new DefaultRetryPolicy(20 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(order);
    }
}
